import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';

/**
 * POM文件操作工具类
 */
export class PomFileUtils {
    /**
     * 查找指定文件所在的Maven模块的POM文件
     * @param filePath 文件路径
     * @returns POM文件路径，如果未找到则返回undefined
     */
    public static async findPomFile(filePath: string): Promise<string | undefined> {
        let currentDir = path.dirname(filePath);
        
        // 向上查找直到找到pom.xml文件或到达根目录
        while (currentDir && currentDir !== path.dirname(currentDir)) {
            const pomPath = path.join(currentDir, 'pom.xml');
            
            if (fs.existsSync(pomPath)) {
                return pomPath;
            }
            
            currentDir = path.dirname(currentDir);
        }
        
        return undefined;
    }
    
    /**
     * 从POM文件中提取项目名称
     * @param pomPath POM文件路径
     */
    public static async extractProjectName(pomPath: string): Promise<string | undefined> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            
            // 尝试从<name>标签获取
            const nameMatch = content.match(/<name>([^<]+)<\/name>/);
            if (nameMatch) {
                return nameMatch[1].trim();
            }
            
            // 如果没有name标签，尝试获取artifactId
            const artifactMatch = content.match(/<artifactId>([^<]+)<\/artifactId>/);
            if (artifactMatch) {
                return artifactMatch[1].trim();
            }
            
            // 都没找到，返回目录名
            return path.basename(path.dirname(pomPath));
        } catch (error) {
            console.error(`解析POM文件失败: ${error}`);
            return undefined;
        }
    }
    
    /**
     * 检查POM文件中是否有指定的依赖
     * @param pomPath POM文件路径
     * @param groupId 依赖的groupId
     * @param artifactId 依赖的artifactId
     */
    public static async hasDependency(pomPath: string, groupId: string, artifactId: string): Promise<boolean> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            const dependencyPattern = new RegExp(
                `<dependency>\\s*<groupId>${groupId}</groupId>\\s*<artifactId>${artifactId}</artifactId>`, 'i'
            );
            
            return dependencyPattern.test(content);
        } catch (error) {
            console.error(`检查依赖失败: ${error}`);
            return false;
        }
    }
    
    /**
     * 添加排除依赖的XML片段
     * @param pomPath POM文件路径
     * @param parentGroupId 父依赖的groupId
     * @param parentArtifactId 父依赖的artifactId
     * @param excludeGroupId 要排除的依赖的groupId
     * @param excludeArtifactId 要排除的依赖的artifactId
     */
    public static async addExclusion(
        pomPath: string, 
        parentGroupId: string, 
        parentArtifactId: string,
        excludeGroupId: string,
        excludeArtifactId: string
    ): Promise<boolean> {
        try {
            const content = await fs.promises.readFile(pomPath, 'utf8');
            
            // 查找父依赖
            const dependencyRegex = new RegExp(
                `(<dependency>\\s*<groupId>${parentGroupId}</groupId>\\s*<artifactId>${parentArtifactId}</artifactId>[^<]*(?:<version>[^<]*</version>)?[^<]*)(?:<exclusions>|</dependency>)`,
                'i'
            );
            
            const exclusionXml = `
    <exclusion>
        <groupId>${excludeGroupId}</groupId>
        <artifactId>${excludeArtifactId}</artifactId>
    </exclusion>`;
            
            let modifiedContent: string;
            
            if (content.match(new RegExp(`<dependency>\\s*<groupId>${parentGroupId}</groupId>\\s*<artifactId>${parentArtifactId}</artifactId>.*?<exclusions>`, 's'))) {
                // 已有exclusions标签
                modifiedContent = content.replace(
                    new RegExp(`(<dependency>\\s*<groupId>${parentGroupId}</groupId>\\s*<artifactId>${parentArtifactId}</artifactId>.*?<exclusions>)`, 's'),
                    `$1${exclusionXml}`
                );
            } else {
                // 没有exclusions标签
                modifiedContent = content.replace(
                    dependencyRegex,
                    `$1<exclusions>${exclusionXml}
    </exclusions></dependency>`
                );
            }
            
            await fs.promises.writeFile(pomPath, modifiedContent);
            return true;
            
        } catch (error) {
            console.error(`添加排除依赖失败: ${error}`);
            return false;
        }
    }
}
